/**
 * @function 用户模块api
 * @author anytao
 * @created 2016-07-15
 * @version 1.0
 */

'use strict';

import Base from './base.js';
import request from 'request';

export default class extends Base {

    /**
     * 返回单条用户记录
     * 编辑接口调用
     */
    async getAction() {
        let userId = this.get('userId');
        let user = {
            id: 0
        };

        if (userId) {
            user = await this.model('user').where({
                id: userId
            }).find();
        }

        return this.json(user);

        // let tokenService = think.service('token');
        // let tokenServiceInstance = new tokenService();
        // let data = this.get();
        // let token = tokenServiceInstance.createToken({
        //     name: 'anytao',
        //     password: '1234'
        // });
        // think.log(token);
        // let verifyResult = tokenServiceInstance.verifyToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYW55dGFvIiwicGFzc3dvcmQiOiIxMjM0IiwiaWF0IjoxNDY4NTY1MzEyfQ.Fltv5dMCFAmVCLvICBqaWZzdg768K8m0ytBH4Huq4jE');
        // think.log(verifyResult);
        // //let users= await this.model('user').select();
        // //think.log(users);
        // this.http.header('token', token);
        // return this.json('hh');
    }

    /**
     * @description 用户登录验证
     * @param {Object} user
     * @return 验证结果
     */
    async loginAction() {

        let user = this.post();
        let userInfo = {};
        let md5Password = think.md5(user.password);

        //记录登录日志
        let log = {};
        log.id = null;
        log.type - 'login';
        log.ipAddress = this.ip();
        log.userAgent = this.userAgent();
        log.url = this.http.url;
        log.createTime=think.datetime();
        log.userName = JSON.stringify(user);

        //写入日志
        request.post('http://127.0.0.1:8360/api/log/add', {
            form: {
                log: JSON.stringify(log)
            }
        }, function(err, httpResponse, body) {
            if (err) {
                think.error(err);
            } else {
                think.log(body);
            }
        });

        let result = await this.model("user").where({
            name: user.username
        }).find();

        if (think.isEmpty(result)) {
            return this.fail('用户名不存在');
        }

        userInfo.username = user.username;
        userInfo.password = md5Password;

        if (result.password == md5Password) {
            let tokenService = think.service('token');
            let tokenServiceInstance = new tokenService();
            let token = tokenServiceInstance.createToken(userInfo);
            this.http.header('token', token);
            await this.session('userInfo', userInfo);
            return this.success('登录成功');
        } else {
            return this.fail('用户名或密码错误');
        }
    }

    /**
     * @description 用户列表页
     * @param 
     * @return 
     */
    async listAction() {

        let search = this.post(); //前端传入的搜索条件

        let query = {}; //后端查询条件对象
        let order = {}; //排序对象
        if (!think.isEmpty(search.name)) {
            query.name = ['like', '%' + search.name + '%'];
        }

        if (!think.isEmpty(search.nickname)) {
            query.nickname = ['like', '%' + search.nickname + '%'];
        }

        if (!think.isEmpty(search.orderField)) {
            order[search.orderField] = search.orderDirection;
        }

        // let users = await this.model('user').field('*').select();
        let users = await this.model('user')
            .order(order)
            .where(query)
            .page(this.post('pageCurrent'), this.post('pageSize') || 15)
            .countSelect();
        // think.log(users);
        users.data.forEach(function(user) {
            user.created_at = think.datetime(user.created_at);
            user.updated_at = think.datetime(user.updated_at);
        });
        users.pageCurrent = users.currentPage; //当前页数
        users.total = users.count; //总记录
        users.list = users.data; //返回数据
        delete users.data;
        return this.json(users);
    }

    /**
     * @description 编辑用户
     * @param 
     * @return 
     */
    async editAction() {
        let result = {
            "statusCode": "200",
            "message": "新增成功",
            "tabid": "table, table-fixed",
            "closeCurrent": true,
            "forward": "",
            "forwardConfirm": ""
        };
        let user = this.post();
        think.log(user);
        let userId = 0;
        if (user.id == 0) {
            user.id = null;
            user.password = think.md5('123');
            user.created_at = think.datetime();
            userId = await this.model('user').add(user);
        } else {
            result.message = "编辑成功";
            user.updated_at = think.datetime();
            userId = await this.model('user').where({
                id: user.id
            }).update(user);
        }
        if (userId) {
            return this.json(result);
        } else {
            result.statusCode = "300";
            result.message = "新增失败,错误信息:" + userId;
            return this.json(result);
        }
    }

    /**
     * @description 删除用户
     * @param 
     * @return 
     */
    async deleteAction() {

        let userIds = this.post('userIds');
        let result = {
            statusCode: "200",
            message: "删除成功",
            userIds: userIds
        };

        let deleteMsg = await this.model('user').where({
            id: ["IN", userIds]
        }).delete();
        return this.json(result);
    }
}